package com.ajavaer.framework.common.tools;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class LoadJsTools {

    public static <T> T load(String js) throws ScriptException {
        String scriptPath = LoadJsTools.class.getResource(js).getFile();
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
        String eval = "load(\"{0}\")";
        return (T) nashorn.eval(StringTools.format(eval, scriptPath));
    }

    public static <T> T runJs(String js) throws ScriptException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
        String eval = "eval(\"{0}\")";
        return (T) nashorn.eval(StringTools.format(eval, js));
    }
}
